package com.example.woke1;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.baoyz.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.google.gson.Gson;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.woke.data.Data_askresult;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.wokeMy.view.base.BaseActivity;
import com.wokeMy.view.model.Constant;
import com.wokeMy.view.util.Util;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import cn.xl.xxl.imagecache.ImageLoader;

public class FriendsActivity extends BaseActivity implements OnClickListener {


	private SwipeMenuListView mListView;
//	private ArrayList<String> datalist = new ArrayList<String>();
	private Friendadter adapter;
	private MyApp application;
	private ArrayList<Data_askresult> datalist = new ArrayList<Data_askresult>();
	private String fromid = "";//���������ظ��������Ϣ
//	private int currontpos ;//����ĵڼ�
	private AlertDialog alertDialog;
	private ImageLoader imageLoader;
	private ProgressBar mBar;
	private Datas_load loaded;
	Dialog dialog;

	@Override
	public void setContentView() {
		                       setContentView(R.layout.activity_friends);
	}

	@Override
	public void initView() {
	imageLoader = new ImageLoader(this);
	application = (MyApp) getApplication();
	intview();
	}

	@Override
	public void initData() {

	}

	@Override
	public void initActivity() {

	}

	private void intview() {
		findViewById(R.id.avfriends_text_phonef).setOnClickListener(this);
		findViewById(R.id.avfriends_text_nearby).setOnClickListener(this);
		findViewById(R.id.avfriend_image_back).setOnClickListener(this);
		mListView = (SwipeMenuListView) findViewById(R.id.avfriend_listview);
		mBar = (ProgressBar) findViewById(R.id.avnewfrindakd_progress_bar);
		getnewfriend();
		dialog=Util.createLoadingDialog(FriendsActivity.this);
		sqingList();
	}

	@Override
	protected void onDestroy() {
		imageLoader.clearCache();
		imageLoader.clearMemoryCache();
		super.onDestroy();
	}

	private void agreeadd(final int index, String id, final int position) {
		AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(FriendsActivity.this);
        ahc.setCookieStore(myCookieStore);
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "user");
		if(index == 0){
			params.put("a", "addFriden");
		}else if(index == 1){
			params.put("a", "rejectFriden");
		}else{
			params.put("a", "delNewfriden");
		}
		params.put("id", id);
		Log.e("params", params.toString());
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				Log.e("同意", "请求"+response);
				try {
					String flag = response.getString("flag");
					String info = response.getString("info");
					if(flag.equals("success")){
//						if(index == 0){
//							datalist.get(position).status = "2";
//							adapter.notifyDataSetChanged();
//							Toast.makeText(FriendsActivity.this, ""+info, Toast.LENGTH_SHORT).show();
//						}else if(index == 1){
//							datalist.get(position).status = "3";
//							adapter.notifyDataSetChanged();
//							Toast.makeText(FriendsActivity.this, ""+info, Toast.LENGTH_SHORT).show();
//						}else{
//							datalist.remove(position);
//							adapter.notifyDataSetChanged();
//						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
				Log.e("上传", "手机号失败"+responseString);
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mBar.setVisibility(View.VISIBLE);
			}

			@Override
			public void onFinish() {
				super.onFinish();
				mBar.setVisibility(View.GONE);
			}
		});
	}

	private void createMenu1(SwipeMenu menu) {
		SwipeMenuItem openItem = new SwipeMenuItem(
				getApplicationContext());
		openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
				0xCE)));
		openItem.setWidth(dp2px(90));
		openItem.setTitle("拒绝");
		openItem.setTitleSize(18);
		openItem.setTitleColor(Color.WHITE);
		menu.addMenuItem(openItem);
		int id = openItem.getId();
		SwipeMenuItem deleteItem = new SwipeMenuItem(
				getApplicationContext());
		deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
				0x3F, 0x25)));
		deleteItem.setWidth(dp2px(90));
		deleteItem.setTitle("删除");
		deleteItem.setTitleColor(Color.WHITE);
		deleteItem.setTitleSize(18);
		menu.addMenuItem(deleteItem);
		}

	private void createMenu2(SwipeMenu menu) {
		SwipeMenuItem openItem = new SwipeMenuItem(
				getApplicationContext());
		openItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
				0x3F, 0x25)));
		openItem.setWidth(dp2px(90));
		openItem.setTitle("删除");
		openItem.setTitleSize(18);
		openItem.setTitleColor(Color.WHITE);
		menu.addMenuItem(openItem);
		}

	private void notifardata() {
		SwipeMenuCreator creator = new SwipeMenuCreator() {
			@Override
			public void create(SwipeMenu menu) {
				switch (menu.getViewType()) {
				case 0:
					createMenu2(menu);
					break;
				case 1:
					createMenu1(menu);
					break;
//				case 2:
//					createMenu2(menu);
//					break;
				}
			}
		};

		mListView.setMenuCreator(creator);

		// step 2. listener item click event
		mListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
//				currontpos = position;
				Data_askresult askresult = datalist.get(position);
//				if(menu.getViewType() == 0){
//					Log.e("1", "1");
//					agreeadd(3, askresult.id,position);
//				}else{
//					switch (index) {
//					case 0:
//						// open
//						Log.e("0", "1");
//						agreeadd(1,askresult.id,position);
////					Toast.makeText(FriendsActivity.this,askresult+"��ʾ�������", Toast.LENGTH_SHORT).show();
////					open(item);
//						break;
//					case 1:
//						// delete
////					delete(item)
//						Log.e("0", "2");
//						agreeadd(3,askresult.id,position);
//						break;
//					}
//				}
				return true;
			}
		});

	}


	private void getnewfriend() {
		if(application.getDatas_load ()==null)return;
		AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(FriendsActivity.this);
        ahc.setCookieStore(myCookieStore);
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "user");
		params.put("a", "newFridenlist");
		params.put("userid", application.getDatas_load().getId());
		Log.e("params", params.toString());
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
//				Log.e("�º����б�", "����"+response);
				try {
					String flag = response.getString("flag");
					if(flag.equals("success")){
						JSONObject object = response.getJSONObject("data");
						JSONArray jsonArray = object.getJSONArray("data");
						for (int i = 0; i < jsonArray.length(); i++) {
							JSONObject object2 = jsonArray.getJSONObject(i);
							String id = object2.getString("id");
							String touser = object2.getString("touser");
							String fromuser = object2.getString("fromuser");
							String head = object2.getString("head");
							String status = object2.getString("status");
							String name = object2.getString("name");

							fromid = fromuser;

//							Data_askresult list = new Data_askresult(id, touser,fromuser, head, status, name);
//							datalist.add(list);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

				if(datalist.size() > 0){
					adapter = new Friendadter();
					mListView.setAdapter(adapter);
					notifardata();
//					adapter.notifyDataSetChanged();
				}

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
				Log.e("上传", "手机号失败"+responseString);
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
			}

			@Override
			public void onFinish() {
				super.onFinish();
			}
		});
	}

	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}


	class Friendadter extends BaseAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return datalist.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public int getViewTypeCount() {
			// TODO Auto-generated method stub
			return 2;
		}

		@Override
		public int getItemViewType(int position) {
			// TODO Auto-generated method stub
//			int parseInt = Integer.parseInt(datalist.get(position).status);
//			Log.e("第"+position, "类型"+parseInt);
//			if(parseInt != 1){
//				parseInt = 0;
//			}else{
//				parseInt = 1;
//			}
			return 1;
		}

		public class ViewHolder{
			TextView username;
			ImageView textresult;
			TextView textinfo;
			ImageView mIcon ;

			public ViewHolder(View view) {
				username = (TextView) view.findViewById(R.id.item_friden_textname1);
				textinfo = (TextView) view.findViewById(R.id.item_friden_textinfo1);
				textresult = (ImageView) view.findViewById(R.id.item_friden_result1);
				mIcon = (ImageView) view.findViewById(R.id.avuserinfo_image_inco1);
				view.setTag(this);
			}

		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				convertView = View.inflate(getApplicationContext(),
						R.layout.item_friend_forf1, null);
				new ViewHolder(convertView);
			}
			ViewHolder holder = (ViewHolder) convertView.getTag();
//			Holder holder = null;
//			if(convertView == null){
//				holder = new Holder();
//				convertView = getLayoutInflater().inflate(R.layout.item_friend_forf1, null);
//				holder.username = (TextView) convertView.findViewById(R.id.item_friden_textname1);
//				holder.textinfo = (TextView) convertView.findViewById(R.id.item_friden_textinfo1);
//				holder.textresult = (TextView) convertView.findViewById(R.id.item_friden_result1);
//				convertView.setTag(holder);
//			}else{
//				 holder = (Holder) convertView.getTag();
//			}
			final Data_askresult askresult = datalist.get(position);
			holder.username.setText(askresult.getName());
//			imageLoader.DisplayImage("http://"+askresult.head, holder.mIcon, false, true, true,0);
//			if(askresult.status.equals("1")){
//				holder.textinfo.setText("请求加您为好友");
//				holder.textresult.setImageDrawable(getResources().getDrawable(R.drawable.avphonef_agree1));
//			}else if(askresult.status.equals("2") && application.getDatas_load().getId().equals(askresult.touser)){
//				holder.textinfo.setText("请求加您为好友");
//				holder.textresult.setImageDrawable(getResources().getDrawable(R.drawable.avphonef_agree4));
//			}else if(askresult.status.equals("2") && !application.getDatas_load().getId().equals(askresult.touser)){
//				holder.textinfo.setText("请求加TA为好友");
//				holder.textresult.setImageDrawable(getResources().getDrawable(R.drawable.avphonef_agree4));
//			}else if(askresult.status.equals("3") && !application.getDatas_load().getId().equals(askresult.touser)){
//				holder.textinfo.setText("拒绝了你的好友请求");
//				holder.textresult.setImageDrawable(getResources().getDrawable(R.drawable.avphonef_agree5));
//			}else if(askresult.status.equals("3") && application.getDatas_load().getId().equals(askresult.touser)){
//				holder.textinfo.setText("请求加您为好友");
//				holder.textresult.setImageDrawable(getResources().getDrawable(R.drawable.avphonef_agree2));
//			}
			holder.textinfo.setText("请求加您为好友");
				holder.textresult.setImageDrawable(getResources().getDrawable(R.drawable.avphonef_agree1));
			holder.textresult.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
//					if(askresult.status.equals("1")){
//						Log.e("dd", "方法");
//						agreeadd(0, askresult.id,position);
//					}
					dialog=Util.createLoadingDialog(FriendsActivity.this);
					tgfriend(datalist.get(position).getUser_id());
				}
			});


			return convertView;
		}

	}


	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		switch (v.getId()) {
		case R.id.avfriends_text_phonef:
			intent.setClass(FriendsActivity.this, PhonefriendaddActivity.class);
			startActivity(intent);
			break;

		case R.id.avfriends_text_nearby:
			intent.setClass(FriendsActivity.this, NearbyfriendActivity.class);
			startActivity(intent);
			break;

		case R.id.avfriend_image_back:
			finish();
			break;

		default:
			break;
		}
	}

//	private void aralogid(final String id){
//		   alertDialog = new AlertDialog.Builder(FriendsActivity.this). 
//	                setTitle("ɾ��������¼"). 
////	                setMessage(kll). 
////	                setIcon(R.drawable.ic_launcher). 
//	                setPositiveButton("ȷ��", new DialogInterface.OnClickListener() { 
//	                    @Override 
//	                    public void onClick(DialogInterface dialog, int which) { 
//	                    	agreeadd(3, id);
//	                    	alertDialog.dismiss();
//	                    } 
//	                }). 
//	                setNegativeButton("ȡ��", new DialogInterface.OnClickListener() { 
//	                    @Override 
//	                    public void onClick(DialogInterface dialog, int which) { 
//	                    	alertDialog.dismiss();
//	                        // TODO Auto-generated method stub  
//	                    } 
//	                }).create(); 
//	        alertDialog.show(); 
//	}

//	@Override
//	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
//			long arg3) {
//		currontpos = arg2;
//		aralogid(datalist.get(arg2).id);
//		return false;
//	}
	//申请好友列表

	public void sqingList() {
	loaded=application.getDatas_load();
	AsyncHttpClient ahc = new AsyncHttpClient();
	RequestParams params = new RequestParams();
	params.put("user_id",loaded.getId());
	Log.e("申请好友列表 params",params.toString());
	Log.e("申请好友列表 url", Constant.YXFADDLIST_URL);
	//url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
	ahc.post(Constant.YXFADDLIST_URL, params, new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int i, Header[] headers, byte[] bytes) {
			Util.closeDialog(dialog);
			//判断状态码
			if(i == 200){
				//获取结果
				try {
					String result = new String(bytes, "utf-8");
					//                        Toast.makeText(CreditRepayActivity.this, result, Toast.LENGTH_SHORT).show();
					Log.e("申请好友列表 Result", result);
					try {
						datalist.clear();
						JSONObject jsonObject = new JSONObject(result);
						if (jsonObject.getString("flag").equals("success")) {
							JSONArray s = jsonObject.getJSONObject("data").getJSONArray("data");
							Gson gson = new Gson();
							for (int i1 = 0; i1 < s.length(); i1++) {
								Data_askresult data_askresult = gson.fromJson(s.getString(i1), Data_askresult.class);
								if (!(loaded.getId().equals(data_askresult.getUser_id())))  {
								datalist.add(data_askresult);
								}

							}
//								if(datalist.size() > 0) {
//
//								}
							adapter = new Friendadter();
							mListView.setAdapter(adapter);
							notifardata();
						}

					} catch (JSONException e) {
						e.printStackTrace();
					}

				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		@Override
		public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
			Util.closeDialog(dialog);
			tishi("请求失败");
			Log.e("onFailure",new String(bytes).toString());
		}
	});
}

	//通过好友申请

	public void tgfriend(String from_user_id ) {
	loaded=application.getDatas_load();
	AsyncHttpClient ahc = new AsyncHttpClient();
	RequestParams params = new RequestParams();
	params.put("user_id",loaded.getId());
	params.put("from_user_id",from_user_id);
	Log.e("通过好友申请 params",params.toString());
	Log.e("通过好友申请 url", Constant.YXTGHYLB_URL);
	//url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
	ahc.post(Constant.YXTGHYLB_URL, params, new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int i, Header[] headers, byte[] bytes) {
			Util.closeDialog(dialog);
			//判断状态码
			if(i == 200){
				//获取结果
				try {
					String result = new String(bytes, "utf-8");
					//                        Toast.makeText(CreditRepayActivity.this, result, Toast.LENGTH_SHORT).show();
					Log.e("通过好友申请 Result", result);
					try {

						JSONObject jsonObject = new JSONObject(result);
						String indo=jsonObject.getString("info");

						if (jsonObject.getString("flag").equals("success")){

							tishiToast("添加成功");
							datalist.clear();
							sqingList();
							return;

							}
							tishi(indo);

					} catch (JSONException e) {
						e.printStackTrace();
					}

				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		@Override
		public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

			Util.closeDialog(dialog);
			tishiToast("请求失败");
			Log.e("onFailure",new String(bytes).toString());
		}
	});
}

}
